package com.example.demowx.controller;

import com.example.demowx.service.DemoWxService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("wx")
public class DemoWxController {

    @Value("${demo.token}")
    private String token;

    @Resource
    private DemoWxService demoWxService;

    @GetMapping("test")
    public void demoTest(HttpServletRequest request, HttpServletResponse response) {

        //第二步：验证消息的确来自微信服务器
        //开发者提交信息后，微信服务器将发送GET请求到填写的服务器地址URL上，GET请求携带参数如下表所示：
        //signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        //timestamp 时间戳
        //nonce 随机数
        //echostr 随机字符串
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        System.out.println(signature);
        System.out.println(timestamp);
        System.out.println(nonce);
        System.out.println(echostr);
        //开发者通过检验signature对请求进行校验（下面有校验方式）。若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败。加密/校验流程如下：
        try {
            if (demoWxService.check(signature, timestamp, nonce, token)) {

                System.out.println("微信接入成功");
                PrintWriter writer = null;
                writer = response.getWriter();
                //原样返回echostr参数内容
                writer.print(echostr);
                writer.flush();
                writer.close();
            } else {
                System.out.println("微信接入失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("test")
    public void demoTestPost(HttpServletRequest request,HttpServletResponse response){

        try {
            request.setCharacterEncoding("utf8");
            response.setCharacterEncoding("utf8");
            Map<String,String> parms= demoWxService.getParams(request.getInputStream());
            System.out.println(parms);
            //微信回复格式为xml:
            //String str="<xml><ToUserName><![CDATA["+parms.get("FromUserName")+"]]></ToUserName><FromUserName><![CDATA["+parms.get("ToUserName")+"]]></FromUserName><CreateTime>"+ LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")) +"</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[你好]]></Content></xml>";
            //准备回复的xml数据包
            String respXml= demoWxService.getRespose(parms);
            PrintWriter writer = response.getWriter();
            writer.print(respXml);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("测试接受消息");
    }
}
